package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.cache.vo.StrategyStatisVO;
import cn.wolfcode.luowowo.domain.Destination;
import cn.wolfcode.luowowo.domain.Strategy;
import cn.wolfcode.luowowo.domain.StrategyCatalog;
import cn.wolfcode.luowowo.domain.StrategyTheme;
import cn.wolfcode.luowowo.query.StrategyQuery;
import cn.wolfcode.luowowo.repository.StrategyCatalogRepository;
import cn.wolfcode.luowowo.repository.StrategyRepository;
import cn.wolfcode.luowowo.repository.StrategyThemeRepository;
import cn.wolfcode.luowowo.service.IDestinationService;
import cn.wolfcode.luowowo.service.IStrategyService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class StrategyServiceImpl implements IStrategyService{
    @Autowired
    private StrategyRepository strategyRepository;
    @Autowired
    private StrategyThemeRepository strategyThemeRepository;
    @Autowired
    private StrategyCatalogRepository catalogRepository;
    @Autowired
    private IDestinationService destinationService;
    @Autowired
    private MongoTemplate template;
    @Override
    public List<Strategy> list() {

        return strategyRepository.findAll();
    }

    @Override
    public Page<Strategy> query(StrategyQuery qo) {
        //条件
        //通过目的地方式查询
        Query query = new Query();
        if(StringUtils.hasLength(qo.getDestId())){
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        //主题
        if(StringUtils.hasLength(qo.getThemeId())){
            query.addCriteria(Criteria.where("themeId").is(qo.getThemeId()));
        }

        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.DESC, "_id");

        return DBHelper.query(template, Strategy.class, query, pageable);
    }

    @Override
    public void saveOrUpdate(Strategy strategy) {
        //主题属性
        StrategyTheme strategyTheme = strategyThemeRepository.findById(strategy.getThemeId()).orElse(null);
        strategy.setThemeName(strategyTheme.getName());
        //分类属性
        StrategyCatalog strategyCatalog = catalogRepository.findById(strategy.getCatalogId()).orElse(null);
        strategy.setCatalogName(strategyCatalog.getName());
        //目的地的id属性
        strategy.setDestId(strategyCatalog.getDestId());
        //目的地的name属性
        strategy.setDestName(strategyCatalog.getDestName());
        //是否国外
        List<Destination> toasts = destinationService.getToasts(strategyCatalog.getDestId());
        if(toasts != null && toasts.size() > 0){
            strategy.setIsabroad("中国".equals(toasts.get(0).getName())?Strategy.ABROAD_NO:Strategy.ABROAD_YES);
        }
        if(!StringUtils.hasLength(strategy.getId())){
            strategy.setCreateTime(new Date());
            strategy.setId(null);
            strategyRepository.save(strategy);
        }else {
            //注意: MongoDB的更新是全量更新,所以操作是先查 再替换 再更新
            //但此时无需注意其他数据,因为刚好页面传过来的参数是与数据库中列的个数是一样的,
            //当后续还有其他情况时则再看,
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(strategy.getId()));
            DBHelper.update(template,query,strategy,"destId","destName","themeId",
                    "themeName","catalogId","catalogName",
                    "title","subTitle","summary","coverUrl",
                    "isabroad","state","content"
            );
        }
    }

    @Override
    public void save(Strategy strategy) {
        strategy.setId(null);
        strategyRepository.save(strategy);
    }

    @Override
    public void update(Strategy strategy) {
        strategyRepository.save(strategy);
    }

    @Override
    public void delete(String id) {
        strategyRepository.deleteById(id);
    }

    @Override
    public Strategy get(String id) {
        /*Optional<Strategy> optional = strategyRepository.findById(rid);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;*/
        return strategyRepository.findById(id).orElse(null);
    }

    @Override
    public void updateState(int state, String id) {
        /*Strategy strategy = this.select(id);
        strategy.setState(state);
        strategyRepository.save(strategy);*/
        //查询
        //替换
        //更改
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        //db.users.update({},{$set:{state:1}})
        //等价于: $set
        Update update = new Update();
        update.set("state",state);
        //部分字段更新
        template.updateMulti(query,update,Strategy.class);
        //-----------------------

    }

    @Override
    public List<Strategy> getDest(String destId) {
        //按点击量排序的方式获取攻略集合
        //List<Strategy> sList = strategyRepository.findByDestIdOrderByViewnumDesc(destId);
        //再截取前3个集合放入一个新集合
        //List<Strategy> strategies = sList.subList(0, 3);
        //再返回即可
        Pageable pageable = PageRequest.of(0,3, Sort.Direction.DESC,"viewnum");
        //return strategyRepository.findByDestIdOrderByViewnumDesc(destId).subList(0, 3);
        return strategyRepository.findByDestId(destId,pageable);
    }

    @Override
    public List<Strategy> getCatalogList(String id) {
        return strategyRepository.findByCatalogId(id);
    }

    @Override
    public void updateVO(StrategyStatisVO strategyStatisVO) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(strategyStatisVO.getStrategyId()));
        Update update = new Update();
        update.set("viewnum",strategyStatisVO.getViewnum());
        update.set("replynum",strategyStatisVO.getReplynum());
        update.set("favornum",strategyStatisVO.getFavornum());
        update.set("sharenum",strategyStatisVO.getSharenum());
        update.set("thumbsupnum",strategyStatisVO.getThumbsupnum());
        //部分字段更新
        template.updateMulti(query,update,Strategy.class);
    }

    @Override
    public List<Strategy> getByDestName(String destName) {
        return strategyRepository.findByDestName(destName);
    }

}
